package com.sjb.mianshiya.Once;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * @Author:sjb
 * @CreateTime:2024-11-22
 * @Description: 反爬虫方法测试
 * @Version：1.0
 */
public class RequestRateLimiter {

    // 用户存储每个用户的访问计数器
    public ConcurrentHashMap<String, LongAdder> userRequestCounts = new ConcurrentHashMap<>();

    // 统计的时间间隔 比如每分钟统计一次计数
    private final long interval;


    public RequestRateLimiter(long intervalInSeconds) {
        this.interval = intervalInSeconds;
        startRestTask();
    }


    /**
     * 每次用户调用访问时先调用此方法
     * @param userId
     */
    public void recordRequest(String userId){
        // 获取或者初始化用户的访问计数器
        userRequestCounts.computeIfAbsent(userId, key -> new LongAdder()).increment();
    }

    /**
     * 获取用户的当前访问次数
     * @param userId
     * @return
     */
    public long getRequestCount(String userId){
        return userRequestCounts.getOrDefault(userId,new LongAdder()).sum();
    }

    /**
     * 定期重置每个用户的访问次数
     */
    private void startRestTask(){
        // 定时任务 每隔指定的时间间隔重置次数
        new Thread(() -> {
            while (true){
                try {
                    // 等待指定的时间间隔
                    TimeUnit.SECONDS.sleep(interval);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
                userRequestCounts.clear();
            }
        }).start();
    }

    public static void main(String[] args) {
        RequestRateLimiter requestRateLimiter = new RequestRateLimiter(1);

        requestRateLimiter.recordRequest("user1");
        requestRateLimiter.recordRequest("user2");

        System.out.println("User1's current request count: " + requestRateLimiter.getRequestCount("user1"));
    }
}

